package com.example.common.exception;

import com.example.common.model.ApiResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

// 自定义全局异常处理类
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    /**
     * 自定义异常
     */
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<ApiResponse<?>> handleCustomException(CustomException ex) {
        return ResponseEntity
                   .status(ex.getCode())
                   .body(ApiResponse.error(ex.getCode(), ex.getMessage()));
    }
    
    /**
     * 代码或者逻辑异常 (通用后备)
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse<?>> handleException(Exception ex) {
        return ResponseEntity
                   .status(500)
                   .body(ApiResponse.error(500, "服务器内部错误: " + ex.getMessage()));
    }
}
